#! /usr/bin/env python
#coding=utf-8

from get_month_quarter import *
from get_tasks_develop_report_detail import get_task_plan_delay
#from __future__ import division

db = get_db_connection()

def get_task_plan_status(row,first_day,last_day,req_status):
    
    req_planexecute = get_model('planexecute')
    req_plan = get_model('plan')
    
    settings = Ini('../apps/settings.ini')
    milestone_buffer = dict(settings.PARA.MILESTONE_DELAY_DAY)
#    print 'milestone_buffer',milestone_buffer
    
    day_buffer = milestone_buffer.get('buffer')
#    print 'day_buffer',day_buffer
    #初始化任务状态
    task_status = '1'
    
    task = row.id
    dev_task = row.task_id
    #判断是当前周报批处理还是上周周报重跑，如果是当前周，则计划延迟判断使用today日期
    if last_day>date.today():
        last_day = date.today()
    
    delay = select([req_plan.c.title,
                    req_plan.c.type,
                    req_plan.c.begin_date,
                    req_plan.c.end_date,
                    req_planexecute.c.finish_begin_date,
                    req_planexecute.c.finish_end_date,
                    req_plan.c.weight],
                    and_(req_planexecute.c.task == task,
                            req_plan.c.id == req_planexecute.c.plan,
                            or_(and_(req_plan.c.type == '1',
                                    or_(req_plan.c.begin_date != None,
                                        req_plan.c.end_date != None)
                                        ),
                                and_(req_plan.c.type == '2',
                                    req_plan.c.end_date != None
                                     ),
                                and_(req_plan.c.type == '1',
                                    or_(and_(req_planexecute.c.finish_begin_date >= first_day,
                                             req_planexecute.c.finish_begin_date <= last_day,
                                             req_planexecute.c.finish_end_date  >= first_day,
                                             req_planexecute.c.finish_end_date  <= last_day)
                                        )),
                                and_(req_plan.c.type == '2',
                                    req_planexecute.c.finish_end_date  >= first_day,
                                    req_planexecute.c.finish_end_date  <= last_day)   
                                )
                        ))
    
#    print delay
    delay_rs = delay.execute()
    for row_d in delay_rs:
    #          dev_task,devid,planid,plan_name,plan_date = row_d
        plan_name,type,begin_date,end_date,finish_begin_date,finish_end_date,weight = row_d
            
        if type == '2' and end_date and (end_date <= last_day and (not finish_end_date)):    
            if finish_end_date and ((end_date >=first_day and finish_end_date == end_date) or (end_date < first_day)):
                continue
            else:
                #累计延迟15%的里程碑权重,函数datediff计算两个日期之间的天数
                if not finish_end_date and datediff(row.begin_time,row.end_time)!=0 and float(datediff(end_date,last_day))/datediff(row.begin_time,row.end_time) >= day_buffer:
#                    weight_delay += weight
#                    print 'end_date,last_day',end_date,last_day,row.begin_time,row.end_time
                    plan_status = '5'
                    if cmp(plan_status,req_status) > 0:
                        req_status = plan_status
                    if cmp(plan_status,task_status) > 0:
                        task_status = plan_status
                                                                                
                if finish_end_date:
#                    print '1vvvvvvvvv',dev_task,end_date,finish_end_date
#                    delay_stat = delay_stat+str(dev_task)+'-'+plan_name+'('+u'里程碑计划完成时间:'+str(end_date)[0:10]+'|'+u'实际完成时间:'+str(finish_end_date)[0:10]+')'+';\n'
                    plan_status = '3'
                    if cmp(plan_status,req_status) > 0:
                        req_status = plan_status
                    if cmp(plan_status,task_status) > 0:
                        task_status = plan_status
                    
                else:
#                    print '1dddddddddd',dev_task,end_date,finish_end_date
#                    delay_stat = delay_stat+str(dev_task)+'-'+plan_name+'('+u'里程碑计划完成时间:'+str(end_date)[0:10]+'|'+u'实际完成时间:'+u'未填写'+')'+';\n'
                    plan_status = '3'
                    if cmp(plan_status,req_status) > 0:
                         req_status = plan_status
                    if cmp(plan_status,task_status) > 0:
                         task_status = plan_status
                    
        elif type == '2' and end_date and finish_end_date and finish_end_date>=first_day and finish_end_date <= last_day and end_date>last_day:
            if datediff(row.begin_time,row.end_time)!=0 and float(datediff(end_date,finish_end_date))/datediff(row.begin_time,row.end_time) >= day_buffer:
#                weight_delay += weight
                 plan_status = '4'
                 if cmp(plan_status,req_status) > 0:
                      req_status = plan_status
                 if cmp(plan_status,task_status) > 0:
                      task_status = plan_status
            else:
                plan_status = '2'
                if cmp(plan_status,req_status) > 0:
                    req_status = plan_status
                if cmp(plan_status,task_status) > 0:
                    task_status = plan_status
                
#            print '1wwwwwwwwww',dev_task,end_date,finish_end_date
#            delay_stat = delay_stat+str(dev_task)+'-'+plan_name+'('+u'里程碑计划完成时间:'+str(end_date)[0:10]+'|'+u'实际完成时间:'+str(finish_end_date)[0:10]+')'+';\n'
        if type == '1' and begin_date and (begin_date <= last_day and (not finish_begin_date or finish_begin_date > begin_date)):    
            if finish_begin_date and ((begin_date >=first_day and finish_begin_date == begin_date) or (begin_date < first_day)):
                pass
            else:
                #累计延迟15%的里程碑权重,函数datediff计算两个日期之间的天数
#                print 'begin_date,last_day',begin_date,last_day,row.begin_time,row.end_time,row.id
                if not finish_begin_date and datediff(row.begin_time,row.end_time)!=0 and float(datediff(begin_date,last_day))/datediff(row.begin_time,row.end_time) >= day_buffer:
#                    weight_delay += weight
#                    print 'end_date,last_day',end_date,last_day,row.begin_time,row.end_time                    
                    plan_status = '5'
                    if cmp(plan_status,req_status) > 0:
                         req_status = plan_status
                    if cmp(plan_status,task_status) > 0:
                         task_status = plan_status
                    
                if finish_begin_date:
#                    print '2vvvvvvvvv',dev_task,begin_date,finish_begin_date
#                    delay_stat = delay_stat+str(dev_task)+'-'+plan_name+'('+u'计划开始时间:'+str(begin_date)[0:10]+'|'+u'实际完成时间:'+str(finish_begin_date)[0:10]+')'+';\n'
                    plan_status = '3'
                    if cmp(plan_status,req_status) > 0:
                         req_status = plan_status
                    if cmp(plan_status,task_status) > 0:
                         task_status = plan_status
                    
                else:
#                    print '2ddddddddd',dev_task,begin_date,finish_begin_date
#                    delay_stat = delay_stat+str(dev_task)+'-'+plan_name+'('+u'计划开始时间:'+str(begin_date)[0:10]+'|'+u'实际完成时间:'+u'未填写'+')'+';\n'
                    plan_status = '3'
                    if cmp(plan_status,req_status) > 0:
                         req_status = plan_status
                    if cmp(plan_status,task_status) > 0:
                         task_status = plan_status
                    
        elif type == '1' and begin_date and finish_begin_date and finish_begin_date >= first_day and finish_begin_date <= last_day and begin_date>last_day:
            if datediff(row.begin_time,row.end_time)!=0 and float(datediff(begin_date,finish_begin_date))/datediff(row.begin_time,row.end_time) >= day_buffer:
#                weight_delay += weight
                plan_status = '4'
                if cmp(plan_status,req_status) > 0:
                    req_status = plan_status
                if cmp(plan_status,task_status) > 0:
                    task_status = plan_status
            else:
                plan_status = '2'
                if cmp(plan_status,req_status) > 0:
                    req_status = plan_status
                if cmp(plan_status,task_status) > 0:
                    task_status = plan_status
                                
#            print '2wwwwwwwwww',dev_task,begin_date,finish_begin_date
#            delay_stat = delay_stat+str(dev_task)+'-'+plan_name+'('+u'计划开始时间:'+str(begin_date)[0:10]+'|'+u'实际完成时间:'+str(finish_begin_date)[0:10]+')'+';\n'
        if type == '1' and end_date and (end_date <= last_day and (not finish_end_date)):    
            if finish_end_date and ((end_date >=first_day and finish_end_date == end_date) or (end_date < first_day)):
                continue
            else:
                #累计延迟15%的里程碑权重,函数datediff计算两个日期之间的天数
                if not finish_end_date and datediff(row.begin_time,row.end_time)!=0 and float(datediff(end_date,last_day))/datediff(row.begin_time,row.end_time) >= day_buffer:
#                    weight_delay += weight
#                    print 'end_date,last_day',end_date,last_day,row.begin_time,row.end_time
                    
                    plan_status = '5'
                    if cmp(plan_status,req_status) > 0:
                        req_status = plan_status
                    if cmp(plan_status,task_status) > 0:
                        task_status = plan_status
                    
                if finish_end_date:
#                    print '3vvvvvvvv',dev_task,end_date,finish_end_date
#                    delay_stat = delay_stat+str(dev_task)+'-'+plan_name+'('+u'计划完成时间:'+str(end_date)[0:10]+'|'+u'实际完成时间:'+str(finish_end_date)[0:10]+')'+';\n'
                    plan_status = '3'
                    if cmp(plan_status,req_status) > 0:
                        req_status = plan_status
                    if cmp(plan_status,task_status) > 0:
                        task_status = plan_status
                    
                else:
#                    print '3ddddddddd',dev_task,end_date,finish_end_date
#                    delay_stat = delay_stat+str(dev_task)+'-'+plan_name+'('+u'计划完成时间:'+str(end_date)[0:10]+'|'+u'实际完成时间:'+u'未填写'+')'+';\n'
                    plan_status = '3'
                    if cmp(plan_status,req_status) > 0:
                        req_status = plan_status
                    if cmp(plan_status,task_status) > 0:
                        task_status = plan_status
                    
        elif type == '1' and end_date and finish_end_date and finish_end_date >=first_day and finish_end_date <= last_day and end_date>last_day:
            if datediff(row.begin_time,row.end_time)!=0 and float(datediff(end_date,finish_end_date))/datediff(row.begin_time,row.end_time) >= day_buffer:
#                weight_delay += weight
                plan_status = '4'
                if cmp(plan_status,req_status) > 0:
                    req_status = plan_status
                if cmp(plan_status,task_status) > 0:
                    task_status = plan_status
            else:
                plan_status = '2'
                if cmp(plan_status,req_status) > 0:
                    req_status = plan_status
                if cmp(plan_status,task_status) > 0:
                    task_status = plan_status
                   
#            print '3wwwwwwwwww',dev_task,end_date,finish_end_date
#            delay_stat = delay_stat+str(dev_task)+'-'+plan_name+'('+u'计划完成时间:'+str(end_date)[0:10]+'|'+u'实际完成时间:'+str(finish_end_date)[0:10]+')'+';\n'
#        if task == 2784:
#            print '-------',type,begin_date,end_date,finish_begin_date,finish_end_date,weight
    return req_status,task_status

def get_plan_delay_question_detail():
    P = get_model('planexecute')
    Q = get_model('question')
    req_user = get_model('user')
    #   Notic = get_model('notic')
    #   Tables = get_model('tables')
    #   
    #   table = Tables.get_table(tablename)        
    Q.modified_user.default = None
    
    today = date.today()
    
    #开始处理计划延迟问题生成      
    for row in P.filter(P.c.status == '2'):
        if row.type == '1':
            #阶段
            if row.finish_end_date:
                continue
            else:
                if row.finish_begin_date and row.plan.end_date>=today:
                    continue
        else:
            if row.finish_end_date:
                continue
        #忽略掉'4'(异常终止)和'5'(暂停)
        if row.task.status in ('4', '5'):
            continue
        q = Q.get((Q.c.planexecute==row.id) & (Q.c.status!='F'))

        if not q:
            user_obj = req_user.get(req_user.c.id==row.task._modified_user_)
            if not user_obj:
                assigned =u'用户被删除'
            else:
                assigned=row.task.modified_user.username
            
            q = Q(requirement=row.task._requirement_, task=row._task_,
                title=u'%s计划延迟' % row.plan.title, category='1',
                content=u'%s计划发生延迟，请尽快处理' % row.plan.title,
                owner=row.task._modified_user_, submitter='系统自动',
                assigned=assigned,
                plan_finish_date=date.today() + datetime.timedelta(days=7),
                status='1', priority='3', systems=[row.task._task_sys_],
                planexecute=row.id, owner_sys=row.task._task_sys_,
                tx=row.task.requirement._tx_, kfzx=row.task._kfzx_, need_discuss=True)
            q.save()
            
            #发送消息
            #将任务延迟情况写入message表
            users = set(row.task.task_sys.users.ids())
            users = list(users)
#            users = row.get_receiver_ids(None)
            message_data=[]
            for row1 in users:
                #判断如果该用户无对应用户，则跳过
                a = req_user.get(req_user.c.id == row1)
                if not a:
#                    print row1
                    continue
#                if row1 == 225:
#                    print 'xxxx',users
                task_message = get_init_message_data()
#                task_message['memo'] = str(Tag('a', row.task_id +'-'+ u'任务里程碑延迟:'+delay_stat, href=str('/tasks/develop/'+str(row.id)),target='_blank'))
                task_message['memo'] = str(Tag('a', "<font color='red'>" + u'新增问题:'+q.title+"</font>", href=str('/ticket/questions/view/'+str(q.id)),target='_blank'))
    #            task_message['memo'] = "<font color='red'>"+str(Tag('a', u'任务延迟', href=str('/tasks/develop/list'+'?'+'task_id'+'='+row.task_id),target='_blank'))+"</font>"
                task_message['type'] = '2'
                task_message['user'] = row1
                task_message['read_flag'] = False
                task_message['sender'] = None
                message_data.append(task_message)
            save_new_message(message_data)

    #           obj = Notice(table_id=table, obj_id=instance.id, sender=request.user,
    #               modify_flag=modify_flag, memo=unicode(instance))
    #               
    #           obj.save()
    #           
        else:
            #不存在，或已经发送过同时未关闭，不再发送
            continue
           
    
    
def get_weekreport_detail(month_first_day,month_last_day):
    
    #从settings.ini获取任务类型编号
    settings = Ini('../apps/settings.ini')

    #assignment_type = dict(settings.PARA.ASSIGNMENT_TYPE)
    req_req = get_model('requirement')
    RequirementChange = get_model('requirementchange')
    req_dev = get_model('tasks_develop')
    Plan = get_model('plan')
    PlanExecute = get_model('planexecute')
#    req_res = get_model('researches')
#    req_ndev = get_model('tasks')
    req_detal = get_model('tasks_details')
    WeekReport = get_model('weekreport')
    Question = get_model('question')
    Risk = get_model('risk')
    QuestionHis = get_model('questionhis')
    RiskHis = get_model('riskhis')
    PlanHis = get_model('planhis')
    PlanExecuteHis = get_model('planexecutehis')
    Manage_Requirement_Week = get_model('manage_requirement_week')
#    tasks_milestone = get_model('tasks_milestone')
    req_sys = get_model('system')

#    today = datetime.date.today()
   
    #first_day,last_day = get_week()
    last_day = month_last_day
    first_day = month_first_day
    sevenday = datetime.timedelta(days=7)
    threeday = datetime.timedelta(days=3)
#    print last_day,first_day
    
    id_tmp = select([req_req.c.id,req_req.c.title,req_req.c.req_id,
                     req_req.c.care_level,req_req.c.mode,req_req.c.tx,
                     req_req.c.tx_manager,req_req.c.submitter,
                     req_req.c.contactor,req_req.c.exe_manager,req_req.c.main_sys,
                     req_req.c.modified_date,req_req.c.modified_user],    
                     and_(~req_req.c.id.in_(select([req_req.c.id],
                                            and_(req_req.c.modified_date < first_day,
                                            req_req.c.stage.in_(['FN'])))),
                            req_req.c.stage != 'CL'))
    #print 'id_tmp', id_tmp
    id_tmp_rs = id_tmp.execute()
    #data_tmp = {}
    data={}
    for row in id_tmp_rs:
        id,title,req_id,care_level,mode,tx,tx_manager,submitter,contactor,exe_manager,main_sys,modified_date,modified_user = row
        weekreport_obj = WeekReport.get(and_(WeekReport.c.end_date>=first_day,
                                             WeekReport.c.end_date<=last_day,
                                             WeekReport.c.requirement == id))
        #初始化准开发需求状态
        req_status = '1'
                                            
        if not weekreport_obj:
            weekreport_obj = WeekReport(begin_date = first_day,end_date = last_day,requirement = id)
        
        
        #填写由准开发需求获取的数据
        weekreport_obj.title = title
        weekreport_obj.req_id = req_id
        weekreport_obj.care_level = care_level
        weekreport_obj.mode = mode
        weekreport_obj.tx = tx
        weekreport_obj.tx_manager = tx_manager
        weekreport_obj.submitter = submitter
        weekreport_obj.contactor = contactor
        weekreport_obj.exe_manager = exe_manager
        weekreport_obj.main_sys = main_sys
        weekreport_obj.modified_user = modified_user
        weekreport_obj.modified_date = modified_date
        
        
        #description由用户手工填写
        #获取最近一次投产版本日及该投产版本数量，最近四天内的投产版本作为一个投产版本日期
        dev_obj = req_dev.filter(and_(req_dev.c.requirement == id,
                                      req_dev.c.version_date >= first_day
                                      )).order_by(req_dev.c.version_date.asc()).one()
        if dev_obj:
            weekreport_obj.lastest_version_date = dev_obj.version_date
            weekreport_obj.versions = req_dev.filter(and_(req_dev.c.requirement == id,
                                      req_dev.c.version_date >= dev_obj.version_date,
                                      req_dev.c.version_date <= dev_obj.version_date+threeday,
                                      )).count()
        else:
            weekreport_obj.lastest_version_date = None
            weekreport_obj.versions = 0
        #获取需求变更日期及变更内容
        req_chang_obj = RequirementChange.filter(and_(RequirementChange.c.requirement == id,
                                                    RequirementChange.c.type == '1')
                                                    ).order_by(RequirementChange.c.change_date.desc()).one()
        if req_chang_obj:
            weekreport_obj.req_change_date = req_chang_obj.change_date
            weekreport_obj.req_change_content = req_chang_obj.content
            weekreport_obj.req_change_according = req_chang_obj.according
        #获取方案变更日期及变更内容
        req_chang_obj = RequirementChange.filter(and_(RequirementChange.c.requirement == id,
                                                    RequirementChange.c.type == '2')
                                                    ).order_by(RequirementChange.c.change_date.desc()).one()
        if req_chang_obj:
            weekreport_obj.design_change_date = req_chang_obj.change_date
            weekreport_obj.design_change_content = req_chang_obj.content
            weekreport_obj.design_change_according = req_chang_obj.according
        
        #获取计划投入中心资源、预计执行等
        
        Manage_Requirement_Week_obj = Manage_Requirement_Week.filter(and_(Manage_Requirement_Week.c.req_id == id,
                                                    Manage_Requirement_Week.c.report_type == '1',
                                                    Manage_Requirement_Week.c.report_date>=first_day,
                                                    Manage_Requirement_Week.c.report_date<=last_day)
                                                    ).one()
        if Manage_Requirement_Week_obj:
            if Manage_Requirement_Week_obj.inner_resource_input != 0:
                weekreport_obj.plan_resource_center = Manage_Requirement_Week_obj.inner_resource_num/Manage_Requirement_Week_obj.inner_resource_input
            weekreport_obj.input_center_per = Manage_Requirement_Week_obj.inner_resource_input
            if Manage_Requirement_Week_obj.outer_resource_input != 0:
                weekreport_obj.plan_resource_company = Manage_Requirement_Week_obj.outer_resource_num/Manage_Requirement_Week_obj.outer_resource_input            
            weekreport_obj.input_company_per = Manage_Requirement_Week_obj.outer_resource_input
            weekreport_obj.pre_execute = Manage_Requirement_Week_obj.plan_stat
        #func_passed_per-'功能测试通过率'，测试功能释放后再开发
        #unfunc_passed_per-'非功能测试通过率'，测试功能释放后再开发
        #maintain_passed_per-'运维测试通过率'，测试功能释放后再开发
        
        weekreport_obj.save()
        weekreport_save=weekreport_obj
        
        #开始处理manytomany关系
        sys_obj = req_req.get(and_(req_req.c.id == id))
        if sys_obj:
#            ids = weekreport_obj.systems.ids()
#            for row_ids in ids:
            weekreport_obj.systems.clear()
            weekreport_obj.systems.add(sys_obj.systems.ids())
        

        
        #开始处理任务书的manytomany关系    
        a = list(req_dev.filter(and_(req_dev.c.requirement==id,req_dev.c.assignment != None)
                                ).values(func.distinct(req_dev.c.assignment)))
#        print 'a',a
        b = [ x[0] for x in a]
#        print 'b',b
        weekreport_obj.assignments.clear()        
        weekreport_obj.assignments.add(b)
        
#        weekreport_save = WeekReport(**weekreport_obj)
#        weekreport_save.save()
#        weekreport_obj.save()
#        weekreport_save=weekreport_obj
#        print 'weekreport_save',weekreport_save

        #清理planhis、planexecutehis、riskhis、questionhis等
        del_obj = RiskHis.filter(and_(RiskHis.c.weekreport == weekreport_obj.id))
        for row_del in del_obj:
            row_del.systems.clear()
            RiskHis.remove(and_(RiskHis.c.id == row_del.id))
        
        del_obj = QuestionHis.filter(and_(QuestionHis.c.weekreport == weekreport_obj.id))
        for row_del in del_obj:
            row_del.systems.clear()
            QuestionHis.remove(and_(QuestionHis.c.id == row_del.id))
        
        del_obj = PlanHis.filter(and_(PlanHis.c.weekreport == weekreport_obj.id))
        for row_del in del_obj:
            row_del.systems.clear()
            PlanHis.remove(and_(PlanHis.c.id == row_del.id))
        
        del_obj = PlanExecuteHis.filter(and_(PlanExecuteHis.c.weekreport == weekreport_obj.id))
        for row_del in del_obj:
#            row_del.systems.clear()
            PlanExecuteHis.remove(and_(PlanExecuteHis.c.id == row_del.id))
                
        #开始处理该准开发需求下问题列表
        question_obj = Question.filter(and_(Question.c.requirement == id,
                                           or_(Question.c.status != 'F',
                                               and_(Question.c.status == 'F',
                                                    Question.c.finish_date>=first_day,
                                                    Question.c.finish_date<=last_day))))

        for row in question_obj:
            data = row.to_dict(['requirement','task','category','content','progress','solve_desc','owner','submitter','submit_date','assigned','plan_finish_date','finish_date','status','priority','modified_date','modified_user','title','tx','kfzx','owner_sys'])
            data['weekreport'] = weekreport_save.id
            data['old_id'] = row.id
            
            q_r = QuestionHis(**data)
            q_r.save()
            #开始处理systems的manytomany关系
#            q_r.systems.clear()
            q_r.systems.add(row.systems.ids())
            
#            weekreport_save.questions.add(q_r.id)

        #开始处理该准开发需求下风险列表
        risk_obj = Risk.filter(and_(Risk.c.requirement == id,
                                            or_(Risk.c.status != 'F',
                                                and_(Risk.c.status == 'F',
                                                    Risk.c.modified_date>=first_day,
                                                    Risk.c.modified_date<=last_day))))

        for row in risk_obj:
            data = row.to_dict(['requirement','task','category','content','affect','solve_desc','resolusion','probability','owner','submitter','submit_date','assigned','status','serious','modified_date','modified_user','title','tx','kfzx','owner_sys'])
            data['weekreport'] = weekreport_save.id
            data['old_id'] = row.id
            risk_r = RiskHis(**data)
            risk_r.save()
            #开始处理systems的manytomany关系
#            risk_r.systems.clear()
            risk_r.systems.add(row.systems.ids())
            
#            weekreport_save.risks.add(risk_r.id)
        #开始处理该准开发需求下计划执行情况
        p_dev_obj = req_dev.filter(and_(req_dev.c.requirement == id,
                                        req_dev.c.status != '4',
                                        req_dev.c.status != '5',
                                        or_(req_dev.c.stage != 'FN',
                                            and_(req_dev.c.stage == 'FN',
                                                req_dev.c.modified_date >= first_day))))
#        plan_id_list = []
        for x in p_dev_obj:
            if x:
                #获取准开发需求状态
                req_status,task_status = get_task_plan_status(x,first_day,last_day,req_status)
#                print 'req_status,task_status',x.id,x.task_id,req_status,task_status
#                print weekreport_obj.id
#                if weekreport_obj.id == 1041:
#                    print '++++++++',x.id,req_status,task_status
                
                if not x.version_headerId:
                    version_headerId = x.id
                else:
                    version_headerId = x.version_headerId
                p_plan = Plan.filter(and_(Plan.c.task == x.id,
                                          or_(Plan.c.end_date<=last_day + sevenday,
                                              and_(Plan.c.type == '1',Plan.c.begin_date<=last_day + sevenday))))
                for z in p_plan:
                    if z.end_date > last_day or (z.begin_date and z.begin_date > last_day):
                        planexecute_count_flag = 0
                        
                        p_exec_plan = PlanExecute.filter(and_(PlanExecute.c.plan == z.id))
                        for y in p_exec_plan:
                            if y.finish_end_date and y.finish_end_date < first_day:
                                continue
                            else:
                                planexecute_count_flag = planexecute_count_flag + 1
                        if planexecute_count_flag > 0:
                            data = z.to_dict(['task','title','type','begin_date','end_date','test_type','memo','idn','main_sys','is_public','is_reserved','stage','weight','responsible','modified_date','modified_user'])
                            data['weekreport'] = weekreport_save.id
                            data['parent_task'] = version_headerId
                            data['flag'] = '2'
                            data['old_id'] = z.id
                            plan_r = PlanHis(**data)
    #                        if z['id'] in plan_id_list:
    #                            pass
    #                        else:
                            plan_r.save()
                            
                            plan_r.systems.clear()
                            plan_r.systems.add(z.systems.ids())
                        
#                        plan_id_list.append(z['id'])
#                        weekreport_save.plans.add(plan_r.id)
                    if (z.end_date <= last_day and z.end_date >= first_day) or (z.begin_date and z.begin_date <= last_day  and z.begin_date >= first_day):
                        planexecute_count_flag = 0
                        
                        p_exec_plan = PlanExecute.filter(and_(PlanExecute.c.plan == z.id))
                        for y in p_exec_plan:
                            if y.finish_end_date and y.finish_end_date < first_day:
                                continue
                            if y:
                                data = y.to_dict(['task','plan','type','system','finish_begin_date','finish_end_date','status','memo','submission','delay_classes','delay_reason','modified_date','modified_user','sync_date','desc','executer','finish'])
                                planexecute_count_flag = planexecute_count_flag + 1
                                
                                data['weekreport'] = weekreport_save.id
                                data['old_id'] = y.id
                                plan_exec_r = PlanExecuteHis(**data)
                                plan_exec_r.save()
                        if planexecute_count_flag>0:
                            data = z.to_dict(['task','title','type','begin_date','end_date','test_type','memo','idn','main_sys','is_public','is_reserved','stage','weight','responsible','modified_date','modified_user'])
                            data['weekreport'] = weekreport_save.id
                            data['parent_task'] = version_headerId
                            data['flag'] = '1'
                            data['old_id'] = z.id
                            plan_r = PlanHis(**data)
                            plan_r.save()
                            
                            plan_r.systems.clear()
                            plan_r.systems.add(z.systems.ids())
                        
#                        plan_id_list.append(z['id'])
#                        weekreport_save.plans.add(plan_r.id)
                        
#                        p_exec_plan = PlanExecute.filter(and_(PlanExecute.c.task == x.id))
#                        p_exec_plan = PlanExecute.filter(and_(PlanExecute.c.plan == z.id))
#                        for y in p_exec_plan:
#                            if y.finish_end_date and y.finish_end_date < first_day:
#                                continue
#                            if y:
#                                data = y.to_dict(['task','plan','type','system','finish_begin_date','finish_end_date','status','memo','submission','delay_classes','delay_reason','modified_date','modified_user','sync_date','desc','executer','finish'])
#                                planexecute_count_flag = planexecute_count_flag + 1
#                                
#                                data['weekreport'] = weekreport_save.id
#                                data['old_id'] = y.id
#                                plan_exec_r = PlanExecuteHis(**data)
#                                plan_exec_r.save()
                                
                    if z.end_date <= first_day or (z.begin_date and z.begin_date < first_day and z.end_date > last_day):
                        p_exec_plan = PlanExecute.filter(and_(PlanExecute.c.plan == z.id,PlanExecute.c.finish_end_date == None))
                        if p_exec_plan:
                            data = z.to_dict(['task','title','type','begin_date','end_date','test_type','memo','idn','main_sys','is_public','is_reserved','stage','weight','responsible','modified_date','modified_user'])
                            data['weekreport'] = weekreport_save.id
                            data['parent_task'] = version_headerId
                            data['flag'] = '1'
                            data['old_id'] = z.id
                            plan_r = PlanHis(**data)
                            plan_r.save()
                            
                            plan_r.systems.clear()
                            plan_r.systems.add(z.systems.ids())
                        
#                           plan_id_list.append(z['id'])
#                        weekreport_save.plans.add(plan_r.id)
                            
                        for y in p_exec_plan:
                            if y:
                                data = y.to_dict(['task','plan','type','system','finish_begin_date','finish_end_date','status','memo','submission','delay_classes','delay_reason','modified_date','modified_user','sync_date','desc','executer','finish'])
                                data['weekreport'] = weekreport_save.id
                                data['old_id'] = y.id
                                plan_exec_r = PlanExecuteHis(**data)
                                plan_exec_r.save()
                
                
                #处理计划时间还未到，实际已经完成的计划或里程碑            
                sel_plan_exe = select([PlanExecute.c.id,Plan.c.id],
                                        and_(PlanExecute.c.plan == Plan.c.id,
                                             PlanExecute.c.task == x.id,
                                            or_(and_(Plan.c.type == '1',
                                                    Plan.c.begin_date > last_day,
                                                    PlanExecute.c.finish_begin_date >= first_day,
                                                    PlanExecute.c.finish_begin_date <= last_day),
                                                    and_(Plan.c.type == '2',
                                                    Plan.c.end_date > last_day,
                                                    PlanExecute.c.finish_end_date >= first_day,
                                                    PlanExecute.c.finish_end_date <= last_day)
                                                )))
                rs_sel_plan_exe = sel_plan_exe.execute()
#                print 'sel_plan_exe',sel_plan_exe
                plan_id_list = []
                for row in rs_sel_plan_exe:
                    planexecute_id,plan_id = row
#                    print 'planexecute_id,plan_id',planexecute_id,plan_id
                    p_exec_plan = PlanExecute.filter(and_(PlanExecute.c.id == planexecute_id))
                    for y in p_exec_plan:
                        if y:
                            data = y.to_dict(['task','plan','type','system','finish_begin_date','finish_end_date','status','memo','submission','delay_classes','delay_reason','modified_date','modified_user','sync_date','desc','executer','finish'])
                            data['weekreport'] = weekreport_save.id
                            data['old_id'] = y.id
                            plan_exec_r = PlanExecuteHis(**data)
                            plan_exec_r.save()
                    
                    if plan_id in plan_id_list:
                        pass
                    else:
                        plan_id_list.append(plan_id)
                        p_plan = Plan.filter(and_(Plan.c.id == plan_id))
                        for z in p_plan:
                            data = z.to_dict(['task','title','type','begin_date','end_date','test_type','memo','idn','main_sys','is_public','is_reserved','stage','weight','responsible','modified_date','modified_user'])
                            data['weekreport'] = weekreport_save.id
                            data['parent_task'] = version_headerId
                            data['flag'] = '1'
                            data['old_id'] = z.id
                            plan_r = PlanHis(**data)
                            plan_r.save()
                            
                            plan_r.systems.clear()
                            plan_r.systems.add(z.systems.ids())
                        

        #current_status字段保存
        weekreport_obj.current_status = req_status
        weekreport_obj.save()
        
    return


